from logging.handlers import RotatingFileHandler
from flask import Flask
import logging
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from redis import StrictRedis
from config import config_dic

db = SQLAlchemy()
redis_store = None


def set_log(config_name):
    # 设置日志的记录等级
    logging.basicConfig(level=config_dic[config_name].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指定日志保存路径，每个日志文件的最大大小，保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)


def create_app(config_name):
    app = Flask(__name__)
    set_log(config_name)
    # 链接redis
    global redis_store
    redis_store = StrictRedis(host=config_dic[config_name].REDIS_HOST, port=config_dic[config_name].REDIS_PSRT)
    # 将配置文件使用起来
    app.config.from_object(config_dic[config_name])
    # 开启csrf保护功能，只提供校验,在cookie和表单中放csrf_token是要自己放进去的
    # CSRFProtect(app)
    # 设置session
    Session(app)
    # 可以使用orm
    db.init_app(app)
    from infos.modules.index import index_blu
    app.register_blueprint(index_blu)  # 注册蓝图
    from infos.modules.passport import passport_blu
    app.register_blueprint(passport_blu)
    from infos.utils.commons import index_class
    app.add_template_filter(index_class,'index_class')#点击排行的过滤器
    from infos.modules.news import news_blu
    app.register_blueprint(news_blu)
    from infos.modules.user import user_blu
    app.register_blueprint(user_blu)
    return app
